package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BEncoderStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;
//    用户下单
    @Transactional
    @Override
    public void submit(Orders orders) {
//A. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
//B. 根据当前登录用户id, 查询用户购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
//        判断购物车有无东西
        if(list==null||list.size()<=0){
            throw new CustomException("购物车为空，不能下单");
        }

        //查询用户数据
        User user = userService.getById(userId);
//C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
//        利用MybatisPlus生成订单id
        long orderId = IdWorker.getId();
//准备订单明细集合封装（购物车数据封装到订单明细）
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
//            封装订单明细（从购物车赋值数据）
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetails.add(orderDetail);

//            计算总金融
            BigDecimal cartAmount = shoppingCart.getAmount();//单价
            Integer number = shoppingCart.getNumber();//数量
            BigDecimal multiply = cartAmount.multiply(new BigDecimal(number));//单价x数量
            amount.addAndGet(multiply.intValue());//将小计追加到总金额中
        }
//        准备订单对象
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

//        1.保存订单信息
        save(orders);
//        2.保存订单明细
        orderDetailService.saveBatch(orderDetails);
//        3.清空购物车
        shoppingCartService.remove(queryWrapper);
    }

    @Autowired
    private OrderService orderService;
    @Override
    public Page<OrdersDto> userPage(int page, int pageSize) {
//构造分页构造器对象
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
//条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getOrderTime);
//        执行分页查询
        orderService.page(ordersPage,queryWrapper);

        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> list=records.stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapper1= new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId,id);
            int count = orderDetailService.count(queryWrapper1);
            List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper1);
            ordersDto.setNumber(new BigDecimal(count).toString());
           ordersDto.setOrderDetails(orderDetails);

           return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);
        return ordersDtoPage;
    }



/*
    @Override
    public OrdersDto getByIdOrder(Long id) {
//        查询订单基本信息
        Orders orders = this.getById(id);
        OrdersDto ordersDto = new OrdersDto();
        BeanUtils.copyProperties(orders,ordersDto);

//        查询当前订单对应的订单明细，从orderdetail表中查询
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        ordersDto.setOrderDetails(list);
        return ordersDto;
    }*/
}